import "@/css/modules/dialog.scss"

let template = _.template('<div class="dialog-com <%= classes %>">\
    <div class="dialog-com__shade"></div>\
    <div class="dialog-com__wrap">\
        <div class="dialog-com__panel" style="<%= style %>">\
            <% if(showClose) { %>\
                <span class="dialog-com__close" ka="<%= kaClose %>" ></span>\
            <% } %>\
            <% if(title) { %>\
                <div class="dialog-com__title"><%= title %></div>\
            <% } else { %>\
                <div class="dialog-com__top"></div>\
            <% } %>\
            <% if(text) { %>\
                <div class="dialog-com__text"><%= text %></div>\
            <% } %>\
            <% if(content) { %>\
                <div class="dialog-com__content"><%= content %></div>\
            <% } %>\
            <div class="dialog-com__bottom">\
                <% if(showCancel) { %>\
                    <span data-ka="submit_popup_cannel" class="dialog-com__button dialog-com__cancel" ka="<%= kaCancel %>" ><%= textCancel || "取消" %></span>\
                <% } %>\
                <% if(showEnsure) { %>\
                    <span data-ka="submit_popup_out" class="dialog-com__button dialog-com__ensure" ka="<%= kaEnsure %>" ><%= textEnsure || "确定" %></span>\
                <% } %>\
            </div>\
        </div>\
    </div>\
</div>')

let instance;

const Dialog = {
    open: function (opts) {
        this.close();

        let _this = this;

        let data = Object.assign({
            classes: "",
            style: "",

            title: "",
            content: "",
            text: "",

            textCancel: "取消",
            textEnsure: "确定",

            kaCancel: "",
            kaEnsure: "",
            kaClose: "",

            showClose: false,
            showEnsure: true,
            showCancel: true,

            callbackEnsure: function () { },
            callbackCancel: function () { },
            callbackClose: function () { }

        }, opts);

        let dialogHtml = template(data);
        let jqDialog = instance = $(dialogHtml);


        jqDialog.on("click", ".dialog-com__close", function () {
            if (typeof data.callbackClose == "function") {
                data.callbackClose()
            }

            _this.close();
        }).on("click", ".dialog-com__cancel", function () {
            if (typeof data.callbackCancel == "function") {
                data.callbackCancel()
            }

            _this.close();
        }).on("click", ".dialog-com__ensure", function () {
            if (typeof data.callbackEnsure == "function") {                                
                data.callbackEnsure()
            }

            _this.close();
        })

        $(document.body).append(jqDialog);

    },
    close: function () {
        instance && instance.remove();
    }
}


export default Dialog;